<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
    public function setting()
    {
        return view('user/setting');
    }

     public function settingStore()
    {
         $this->validate(request(),[
            'name' => 'min:3',
        ]);

        $name = request('name');
        if ($name != $user->name) {
            if(\App\User::where('name', $name)->count() > 0) {
                return back()->withErrors(array('message' => '用户名称已经被注册'));
            }
            $user->name = request('name');
        }
        if ($request->file('avatar')) {
            $path = $request->file('avatar')->storePublicly(md5(\Auth::id() . time()));
            $user->avatar = "/storage/". $path;
        }
        $user->save();
        return back();

    }
     public function show()
    {
        //个人信息
        $user = User::withCount(['stars','fans','posts'])->find($user->id);
        //文章列表
        $posts = $user->posts()->orderBy('created_at','desc')->take(10)->get();
        //关注的用户
         $stars = $user->stars;
         $susers = User::whereIn('id',$fans->pluck('star_id'))->withCount(['stars','fans','posts'])->get();
        //粉丝用户
        $fans = $user->fans;
        $fuser = User::whereIn('id',$fans->pluck('fan_id'))->withCount(['stars','fans','posts'])->get();
        return view('user/show',compact('user','posts','susers','fusers'));
    }
    //关注用户
    public function fan()
    {
        $me = \Auth::user();
        $me->doFan($user->id);
        return [
            'error' => 0,
            'msg' => '',
        ];
    }
    //取消关注
     public function unfan()
    {
        $me = \Auth::user();
        $me->doUnFan($user->id);
        return [
            'error' => 0,
            'msg' => '',
        ];
    }
    
}
